import 'package:flutter/material.dart';
import '../services/database_service.dart';

class LotteryScreen extends StatefulWidget {
  const LotteryScreen({super.key});

  @override
  State<LotteryScreen> createState() => _LotteryScreenState();
}

class _LotteryScreenState extends State<LotteryScreen> {
  Set<int> selectedRedBalls = {};
  int? selectedBlueBall;

  Map<String, int>? prizeStats;
  bool _loadingStats = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('双色球选号'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '红球区域 (选择6个数字)',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 10),
              _buildRedBallGrid(),
              const SizedBox(height: 30),
              const Text(
                '蓝球区域 (选择1个数字)',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 10),
              _buildBlueBallGrid(),
              const SizedBox(height: 30),
              _buildSelectedNumbers(),
              const SizedBox(height: 30),
              _buildActionButtons(),
              const SizedBox(height: 12),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: _onQueryPressed,
                  icon: Icon(Icons.search),
                  label: Text('查询历史中奖情况'),
                ),
              ),
              const SizedBox(height: 20),
              if (_loadingStats) const Center(child: CircularProgressIndicator()),
              if (prizeStats != null && !_loadingStats) _buildPrizeStatsTable(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildRedBallGrid() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.red, width: 2),
        borderRadius: BorderRadius.circular(8),
      ),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 6,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
          childAspectRatio: 1,
        ),
        itemCount: 33,
        itemBuilder: (context, index) {
          final number = index + 1;
          final isSelected = selectedRedBalls.contains(number);
          return GestureDetector(
            onTap: () => _onRedBallTap(number),
            child: Container(
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: isSelected ? Colors.red : Colors.red.shade100,
                border: Border.all(
                  color: Colors.red,
                  width: 2,
                ),
              ),
              child: Center(
                child: Text(
                  number.toString().padLeft(2, '0'),
                  style: TextStyle(
                    color: isSelected ? Colors.white : Colors.red,
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildBlueBallGrid() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.blue, width: 2),
        borderRadius: BorderRadius.circular(8),
      ),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 8,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
          childAspectRatio: 1,
        ),
        itemCount: 16,
        itemBuilder: (context, index) {
          final number = index + 1;
          final isSelected = selectedBlueBall == number;
          return GestureDetector(
            onTap: () => _onBlueBallTap(number),
            child: Container(
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: isSelected ? Colors.blue : Colors.blue.shade100,
                border: Border.all(
                  color: Colors.blue,
                  width: 2,
                ),
              ),
              child: Center(
                child: Text(
                  number.toString().padLeft(2, '0'),
                  style: TextStyle(
                    color: isSelected ? Colors.white : Colors.blue,
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildSelectedNumbers() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '已选号码:',
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              const Text('红球: '),
              Expanded(
                child: Text(
                  selectedRedBalls.isEmpty
                      ? '未选择'
                      : selectedRedBalls
                          .toList()
                          .map((e) => e.toString().padLeft(2, '0'))
                          .join(', '),
                  style: const TextStyle(color: Colors.red),
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Row(
            children: [
              const Text('蓝球: '),
              Expanded(
                child: Text(
                  selectedBlueBall == null
                      ? '未选择'
                      : selectedBlueBall.toString().padLeft(2, '0'),
                  style: const TextStyle(color: Colors.blue),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: ElevatedButton(
            onPressed: _clearAll,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.grey.shade300,
            ),
            child: const Text('清空', style: TextStyle(color: Colors.black)),
          ),
        ),
        const SizedBox(width: 16),
        Expanded(
          child: ElevatedButton(
            onPressed: _randomSelect,
            child: const Text('机选'),
          ),
        ),
      ],
    );
  }

  void _onRedBallTap(int number) {
    setState(() {
      if (selectedRedBalls.contains(number)) {
        selectedRedBalls.remove(number);
      } else if (selectedRedBalls.length < 6) {
        selectedRedBalls.add(number);
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('红球最多只能选择6个')),
        );
      }
    });
  }

  void _onBlueBallTap(int number) {
    setState(() {
      selectedBlueBall = selectedBlueBall == number ? null : number;
    });
  }

  void _clearAll() {
    setState(() {
      selectedRedBalls.clear();
      selectedBlueBall = null;
      prizeStats = null;
    });
  }

  void _randomSelect() {
    setState(() {
      selectedRedBalls.clear();
      final allRedNumbers = List.generate(33, (index) => index + 1);
      allRedNumbers.shuffle();
      final List<int> reds = allRedNumbers.take(6).toList();
      reds.sort();
      selectedRedBalls = reds.toSet();
      selectedBlueBall = (DateTime.now().millisecondsSinceEpoch % 16) + 1;
    });
  }

  void _onQueryPressed() {
    if (selectedRedBalls.length != 6 || selectedBlueBall == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先选择6个红球和1个蓝球再查询')),
      );
      return;
    }
    _updatePrizeStats();
  }

  Future<void> _updatePrizeStats() async {
    if (selectedRedBalls.length == 6 && selectedBlueBall != null) {
      setState(() {
        _loadingStats = true;
      });
      final stats = await _queryPrizeStats();
      setState(() {
        prizeStats = stats;
        _loadingStats = false;
      });
    } else {
      setState(() {
        prizeStats = null;
      });
    }
  }

  Future<Map<String, int>> _queryPrizeStats() async {
    final rows = await DatabaseService.getAllLotteryRows();
    int first = 0, second = 0, third = 0, fourth = 0, fifth = 0, sixth = 0;
    for (var row in rows) {
      final reds = [
        row['red_1'],
        row['red_2'],
        row['red_3'],
        row['red_4'],
        row['red_5'],
        row['red_6']
      ].map((e) => int.parse(e)).toSet();
      final blue = int.parse(row['blue']);
      int redMatch = selectedRedBalls.intersection(reds).length;
      bool blueMatch = selectedBlueBall != null && selectedBlueBall == blue;
      // 双色球中奖规则
      if (redMatch == 6 && blueMatch) {
        first++;
      } else if (redMatch == 6) {
        second++;
      } else if (redMatch == 5 && blueMatch) {
        third++;
      } else if (redMatch == 5 || (redMatch == 4 && blueMatch)) {
        fourth++;
      } else if (redMatch == 4 || (redMatch == 3 && blueMatch)) {
        fifth++;
      } else if ((redMatch == 2 && blueMatch) ||
          (redMatch == 1 && blueMatch) ||
          (redMatch == 0 && blueMatch)) {
        sixth++;
      }
    }
    return {
      '一等奖': first,
      '二等奖': second,
      '三等奖(3k)': third,
      '四等奖(200r)': fourth,
      '五等奖(10r)': fifth,
      '六等奖(5r)': sixth,
    };
  }

  Widget _buildPrizeStatsTable() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('历史中奖情况', style: TextStyle(fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Table(
              border: TableBorder.all(),
              children: [
                TableRow(children: [
                  _tableCell('匹配奖等'),
                  _tableCell('开出次数'),
                ]),
                ...prizeStats!.entries.map((e) => TableRow(children: [
                      _tableCell(e.key),
                      _tableCell('${e.value}次'),
                    ])),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _tableCell(String text) => Padding(
        padding: const EdgeInsets.all(8.0),
        child: Text(text, textAlign: TextAlign.center),
      );
}
